<template>
    <div :class="{'ly-is-full':isFull}" class="sys-dictionary">
        <!-- 搜索区域 -->
        <div class="tableSelect" ref="tableSelect">
            <el-form :inline="true" :model="formInline" label-position="left">
                <el-form-item label="关键词：">
                    <el-input 
                        size="default" 
                        v-model.trim="formInline.search" 
                        maxlength="60" 
                        placeholder="输入关键字进行过滤" 
                        clearable 
                        @change="filterCategories" 
                        style="width:200px">
                    </el-input>
                </el-form-item>
                <el-form-item label="">
                    <el-button @click="handleSearch" type="primary" icon="Search">查询</el-button>
                </el-form-item>
                <el-form-item label="">
                    <el-button @click="resetSearch" icon="Refresh">重置</el-button>
                </el-form-item>
                <el-form-item label="">
                    <el-button icon="Plus" type="primary" @click="addCategory" v-show="hasPermission(this.$route.name,'Create')">新增字典分类</el-button>
                </el-form-item>
                <el-form-item label="">
                    <el-button icon="Plus" type="warning" @click="addItem" v-show="hasPermission(this.$route.name,'Create')" :disabled="!selectedCategory">新增字典项</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button icon="Delete" type="danger" @click="handleBatchDelete" v-show="hasPermission(this.$route.name,'Delete')">删除</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 主内容区域 -->
        <div class="dict-content">
            <!-- 左侧字典分类 -->
            <div class="dict-category">
                <div class="category-header">
                    <h3>字典分类</h3>
                </div>
                <div class="category-list" :style="{height: tableHeight + 'px'}">
                    <div 
                        v-for="category in filteredCategories" 
                        :key="category.id"
                        :class="['category-item', {active: selectedCategory && selectedCategory.id === category.id}]"
                        @click="selectCategory(category)">
                        <div class="category-info">
                            <div class="category-name">{{ category.dict_name || category.name }}</div>
                            <div class="category-code">{{ category.dict_code || category.code }}</div>
                        </div>
                        <div class="category-actions">
                            <el-button 
                                type="primary" 
                                text 
                                size="small" 
                                @click.stop="editCategory(category)"
                                v-show="hasPermission(this.$route.name,'Update')">
                                编辑
                            </el-button>
                            <el-button 
                                type="danger" 
                                text 
                                size="small" 
                                @click.stop="deleteCategory(category)"
                                v-show="hasPermission(this.$route.name,'Delete')">
                                删除
                            </el-button>
                        </div>
                    </div>
                    <div v-if="filteredCategories.length === 0" class="empty-data">
                        <el-empty description="暂无字典分类数据" />
                    </div>
                </div>
            </div>

            <!-- 右侧字典项 -->
            <div class="dict-items">
                <div class="items-header">
                    <h3>字典项 <span v-if="selectedCategory">({{ selectedCategory.dict_name || selectedCategory.name }})</span></h3>
                </div>
                <div class="items-table">
                    <el-table
                        :max-height="tableHeight"
                        border
                        :data="itemsData"
                        ref="itemsTable"
                        v-loading="loadingItems"
                        style="width: 100%"
                        @selection-change="handleItemSelectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column type="index" width="70" label="序号">
                            <template #default="scope">
                                <span v-text="getIndex(scope.$index)"></span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="item_name" label="名称" min-width="120">
                            <template #default="scope">
                                {{ scope.row.item_name || scope.row.name }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="item_value" label="键值" min-width="100">
                            <template #default="scope">
                                {{ scope.row.item_value || scope.row.value }}
                            </template>
                        </el-table-column>
                        <el-table-column label="是否有效" min-width="90">
                            <template #default="scope">
                                <el-tag v-if="scope.row.is_active !== undefined ? scope.row.is_active : scope.row.status" type="success">启用</el-tag>
                                <el-tag v-else type="danger">禁用</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sort_order" label="排序" width="80">
                            <template #default="scope">
                                {{ scope.row.sort_order !== undefined ? scope.row.sort_order : scope.row.sort }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip>
                            <template #default="scope">
                                {{ scope.row.remark || scope.row.description }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" width="150">
                            <template #header>
                                <div style="display: flex;justify-content: space-between;align-items: center;">
                                    <div>操作</div>
                                    <div @click="setFull">
                                        <el-tooltip content="全屏" placement="bottom">
                                            <el-icon><full-screen /></el-icon>
                                        </el-tooltip>
                                    </div>
                                </div>
                            </template>
                            <template #default="scope">
                                <el-button 
                                    type="primary" 
                                    text 
                                    size="small" 
                                    @click="editItem(scope.row)"
                                    v-show="hasPermission(this.$route.name,'Update')">
                                    编辑
                                </el-button>
                                <el-button 
                                    type="danger" 
                                    text 
                                    size="small" 
                                    @click="deleteItem(scope.row)"
                                    v-show="hasPermission(this.$route.name,'Delete')">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div v-if="!selectedCategory" class="empty-placeholder">
                        <el-empty description="请先选择左侧字典分类" />
                    </div>
                </div>

                <!-- 分页 -->
                <div class="pagination" v-if="selectedCategory && itemsData.length > 0">
                    <el-pagination
                        @size-change="handleItemsSizeChange"
                        @current-change="handleItemsCurrentChange"
                        :current-page="itemsPagination.page"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="itemsPagination.limit"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="itemsPagination.total">
                    </el-pagination>
                </div>
            </div>
        </div>

        <!-- 字典分类弹窗 -->
        <add-category ref="addCategoryRef" @refreshData="getCategoriesData"></add-category>
        
        <!-- 字典项弹窗 -->
        <add-item ref="addItemRef" @refreshData="getItemsData" :selectedCategory="selectedCategory"></add-item>
    </div>
</template>

<script>
import AddCategory from "./components/addCategory.vue";
import AddItem from "./components/addItem.vue";
import { 
    apiDictCategory, 
    apiDictCategoryDelete,
    apiDictItem,
    apiDictItemDelete
} from '@/api/api'
import { getTableHeight } from "@/utils/util";

export default {
    components: {
        AddCategory,
        AddItem,
    },
    name: 'sysDictionary',
    data() {
        return {
            isFull: false,
            tableHeight: 400,
            loadingCategories: false,
            loadingItems: false,
            formInline: {
                search: ''
            },
            // 字典分类数据
            categoriesData: [],
            filteredCategories: [],
            selectedCategory: null,
            // 字典项数据
            itemsData: [],
            selectedItems: [],
            itemsPagination: {
                page: 1,
                limit: 10,
                total: 0
            }
        }
    },
    methods: {
        // 表格序列号
        getIndex($index) {
            return (this.itemsPagination.page - 1) * this.itemsPagination.limit + $index + 1
        },
        
        // 全屏切换
        setFull() {
            this.isFull = !this.isFull
        },
        
        // 重置搜索
        resetSearch() {
            this.formInline.search = ''
            this.filterCategories()
        },
        
        // 过滤字典分类
        filterCategories() {
            if (!this.formInline.search) {
                this.filteredCategories = [...this.categoriesData]
            } else {
                const keyword = this.formInline.search.toLowerCase()
                this.filteredCategories = this.categoriesData.filter(item => 
                    (item.dict_name || item.name || '').toLowerCase().includes(keyword) || 
                    (item.dict_code || item.code || '').toLowerCase().includes(keyword)
                )
            }
        },
        
        // 选择字典分类
        selectCategory(category) {
            this.selectedCategory = category
            this.getItemsData()
        },
        
        // 新增字典分类
        addCategory() {
            this.$refs.addCategoryRef.open(null, '新增')
        },
        
        // 编辑字典分类
        editCategory(category) {
            this.$refs.addCategoryRef.open(category, '编辑')
        },
        
        // 删除字典分类
        deleteCategory(category) {
            this.$confirm(`您确定要删除字典分类"${category.name}"？删除后该分类下的所有字典项也将被删除！`, {
                closeOnClickModal: false,
                type: 'warning'
            }).then(() => {
                apiDictCategoryDelete(category.id).then(res => {
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        // 如果删除的是当前选中的分类，清空选择
                        if (this.selectedCategory && this.selectedCategory.id === category.id) {
                            this.selectedCategory = null
                            this.itemsData = []
                        }
                        this.getCategoriesData()
                    } else {
                        this.$message.warning(res.message)
                    }
                })
            }).catch(() => {})
        },
        
        // 新增字典项
        addItem() {
            if (!this.selectedCategory) {
                this.$message.warning('请先选择字典分类')
                return
            }
            this.$refs.addItemRef.open(null, '新增')
        },
        
        // 编辑字典项
        editItem(item) {
            this.$refs.addItemRef.open(item, '编辑')
        },
        
        // 删除字典项
        deleteItem(item) {
            this.$confirm(`您确定要删除字典项"${item.name}"？`, {
                closeOnClickModal: false,
                type: 'warning'
            }).then(() => {
                apiDictItemDelete(item.id).then(res => {
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        this.getItemsData()
                    } else {
                        this.$message.warning(res.message)
                    }
                })
            }).catch(() => {})
        },
        
        // 字典项选择变化
        handleItemSelectionChange(selection) {
            this.selectedItems = selection
        },
        
        // 批量删除
        handleBatchDelete() {
            if (this.selectedItems.length === 0) {
                this.$message.warning('请选择要删除的字典项')
                return
            }
            
            this.$confirm(`您确定要删除选中的 ${this.selectedItems.length} 个字典项？`, {
                closeOnClickModal: false,
                type: 'warning'
            }).then(() => {
                const deletePromises = this.selectedItems.map(item => 
                    apiDictItemDelete(item.id)
                )
                
                Promise.all(deletePromises).then(results => {
                    const successCount = results.filter(res => res.code === 200).length
                    if (successCount > 0) {
                        this.$message.success(`成功删除 ${successCount} 个字典项`)
                        this.getItemsData()
                    }
                }).catch(() => {
                    this.$message.error('批量删除失败')
                })
            }).catch(() => {})
        },
        
        // 获取字典分类数据
        async getCategoriesData() {
            this.loadingCategories = true
            try {
                const params = {
                    keyword: this.formInline.search || '',
                    page: 1,
                    per_page: 100  // 获取所有分类
                }
                const res = await apiDictCategory(params)
                this.loadingCategories = false
                if (res.code === 200) {
                    // 处理API返回的数据结构
                    this.categoriesData = res.data?.list || res.data?.data || res.data || []
                    this.filterCategories()
                } else {
                    this.$message.warning(res.message)
                }
            } catch (error) {
                this.loadingCategories = false
                this.$message.error('获取字典分类失败')
                console.error('Get categories error:', error)
            }
        },
        
        // 获取字典项数据
        async getItemsData() {
            if (!this.selectedCategory) {
                this.itemsData = []
                return
            }
            
            this.loadingItems = true
            try {
                const params = {
                    dict_id: this.selectedCategory.id,
                    page: this.itemsPagination.page,
                    per_page: this.itemsPagination.limit
                }
                const res = await apiDictItem(params)
                this.loadingItems = false
                if (res.code === 200) {
                    // 处理API返回的数据结构
                    this.itemsData = res.data?.list || res.data?.data || res.data || []
                    this.itemsPagination.total = res.data?.pagination?.total || res.data?.total || 0
                } else {
                    this.$message.warning(res.message)
                }
            } catch (error) {
                this.loadingItems = false
                this.$message.error('获取字典项失败')
                console.error('Get items error:', error)
            }
        },
        
        // 字典项分页大小变化
        handleItemsSizeChange(val) {
            this.itemsPagination.limit = val
            this.itemsPagination.page = 1
            this.getItemsData()
        },
        
        // 字典项当前页变化
        handleItemsCurrentChange(val) {
            this.itemsPagination.page = val
            this.getItemsData()
        },
        
        // 计算表格高度
        listenResize() {
            this.$nextTick(() => {
                this.getTheTableHeight()
            })
        },
        
        getTheTableHeight() {
            this.tableHeight = getTableHeight(this.$refs.tableSelect?.offsetHeight || 100)
        },
        
        // 处理搜索
        handleSearch() {
            this.getCategoriesData()
        },
    },
    
    created() {
        this.getCategoriesData()
    },
    
    mounted() {
        window.addEventListener('resize', this.listenResize)
        this.$nextTick(() => {
            this.getTheTableHeight()
        })
    },
    
    unmounted() {
        window.removeEventListener("resize", this.listenResize)
    },
}
</script>

<style scoped>
.sys-dictionary {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.dict-content {
    display: flex;
    flex: 1;
    gap: 16px;
    min-height: 0;
}

.dict-category {
    width: 300px;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
}

.category-header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    background: #f5f7fa;
}

.category-header h3 {
    margin: 0;
    font-size: 16px;
    color: #303133;
}

.category-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
}

.category-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    margin-bottom: 8px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.category-item:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
}

.category-item.active {
    border-color: #409eff;
    background-color: #ecf5ff;
}

.category-info {
    flex: 1;
}

.category-name {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
}

.category-code {
    font-size: 12px;
    color: #909399;
}

.category-actions {
    display: flex;
    gap: 8px;
}

.dict-items {
    flex: 1;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
}

.items-header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    background: #f5f7fa;
}

.items-header h3 {
    margin: 0;
    font-size: 16px;
    color: #303133;
}

.items-table {
    flex: 1;
    padding: 16px;
    overflow: hidden;
}

.empty-data,
.empty-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
}

.pagination {
    padding: 16px;
    border-top: 1px solid #e4e7ed;
    display: flex;
    justify-content: center;
}

/* 全屏模式 */
.ly-is-full {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    background: #fff;
    padding: 16px;
}
</style> 